package com.ykt.controller;

import com.jfinal.ext.route.ControllerBind;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.token.TokenManager;
import com.ykt.common.utils.StringUtil;
import com.ykt.model.Admin;
import com.ykt.model.Shop;
import com.ykt.vo.page.TreeNode;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@ControllerBind(controllerKey="/shop")
public class ShopController extends BaseController<Shop>{
	public ShopController(){
		super(Shop.class);
	}
	
	public void grid() {
        int page = getParaToInt("page", 1);
        int rows = this.getParaToInt("rows", 20);
        
        Admin admin = getCurrentUser();
        Map<String, String> params = this.toParaMap();
        if(admin.get(Admin.role_ids)!=null && admin.getStr(Admin.role_ids).equals("6")){
        	params.put("EQ_s.id",admin.getInt(Admin.shopId).toString());
        }
        
        try {
            Page<Shop> data = Shop.dao.pageFindModel(page, rows, params);
            rendDataGrid(data);
        } catch (Exception e) {
            log.error(e);
            rendJson(false, e.getMessage());
        }
    }
	
	@Override
	public void edit() {
        try {
            Long id = this.getParaToLong(0, 0L);
            if (id != 0L) {
                po = get(id);
                List<Record> list = Db.find("select shop_category_id from shop_relate_category where shop_id=?", id);
                if(list.size()>0){
                	List<Integer> sgCatIdList = new ArrayList<Integer>();
                	for(Record r : list){
                		sgCatIdList.add(r.getInt("shop_category_id"));
                	}
                	String sgCatIdStr = StringUtil.join(sgCatIdList, ",");
                	this.setAttr("shopCategoryIdStr", sgCatIdStr);
                }
            } else {
                setAttr("now", new Date());
            }
            TokenManager.createToken(this, tokenName, tokenTout);
            this.setAttr("po", po);
        } catch (Exception e) {
            log.error("编辑异常", e);
        }
    }
	
	@Override
	protected void otherSave(Model<Shop> m) {
		int shopId = m.get("id");
		Db.update("delete from shop_relate_category where shop_id=?", shopId);
		
		String[] shopCategories = this.getParaValues("shopCategories");
		for(String categoryId : shopCategories){
			String sql = "insert into shop_relate_category(shop_id,shop_category_id) values(?,?)";
			Db.update(sql, shopId, Integer.valueOf(categoryId));
		}
	}
	
	/**
	 * 转向摄像头页面
	 */
	public void camera() {
		Long id = this.getParaToLong(0, 0L);
		if (id != 0L) {
            po = get(id);
        } else {
            setAttr("now", new Date());
        }
        TokenManager.createToken(this, tokenName, tokenTout);
        this.setAttr("po", po);
	}
	
	/**
	 * 转向社区服务点页面
	 */
	public void community() {
		Long id = this.getParaToLong(0, 0L);
		if (id != 0L) {
            po = get(id);
        } else {
            setAttr("now", new Date());
        }
        TokenManager.createToken(this, tokenName, tokenTout);
        this.setAttr("po", po);
	}
	
	/**
	 * 下拉列表单选
	 */
	public void combobox() {

        int id = getParaToInt(0, 0);

        List<Record> list = null;
        String sql = "select * from shop ";
        
        if (id == 0){
        	Admin admin = getCurrentUser();
            if(admin.get(Admin.role_ids)!=null && admin.getStr(Admin.role_ids).equals("6")){
            	sql = sql + " where id="+admin.getInt(Admin.shopId)+"";
            }
            
        	list = Db.find(sql);
        }
        else list = Db.find(sql + " where id <>?", id);

        this.renderJson(list);
    }
	
	/**
	 * 下拉列表多选
	 */
	public void combotree() {

		String sql="select id,name from shop";
		
		List<Record> dataList = Db.find(sql);
		List<TreeNode> list = new ArrayList<TreeNode>();
		for(Record r : dataList ){
			TreeNode rootNode = new TreeNode();
			rootNode.setId(r.getInt("id"));
			rootNode.setText(r.getStr("name"));
			rootNode.setIconCls("icon-home");
			rootNode.setCanChk(false);
			list.add(rootNode);
		}
		this.renderJson(list);
	}
	
	/**
	 * 查找社区服务点
	 */
	public void findCommunity() {
		Integer shopId = getParaToInt("shopId", -1);
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("EQ_s.id", shopId.toString());
		
		int page = getParaToInt("page", 1);
        int rows = this.getParaToInt("rows", 20);
        try {
            Page<Shop> data = Shop.dao.pageFindCommunity(page, rows, paramMap);
            rendDataGrid(data);
        } catch (Exception e) {
            log.error(e);
            rendJson(false, e.getMessage());
        }
	}
	
	/**
	 * 保存社区服务点
	 */
	public void savaCommunity(){
		String shopId = this.getPara("shopId");
		String cameraId = this.getPara("communityId");
		
		String sql = "SELECT * FROM community_shop c WHERE c.community_id = ? AND c.shop_id = ?";
		List<Shop> communityShop = Shop.dao.find(sql, cameraId,shopId);
		
		String msg = "保存成功！";
		Integer id = null;
		if (communityShop != null && communityShop.size()>0) {
			msg = "此社区服务点已经存在！";
		}else{
			String insertSql = "insert into community_shop(community_id,shop_id)values(?,?)";
			id = Db.update(insertSql, cameraId, shopId);
			msg = "保存成功！";
			//id = shop.getInt("id");
		}
		rendJson(true, msg, id, new Random().nextLong());
	}
	
	/**
	 * 删除社区服务点
	 */
	public void deleteCommunity(){
		String id = this.getPara("id");
//		String deleteSql = "delete from community_shop wehre id=?";
//		Db.update(deleteSql, id);
		Db.deleteById("community_shop", id);
		String msg = "删除成功！";
		id = null;
		rendJson(true, msg, id, new Random().nextLong());
	}
}
